import poplib
import random
import traceback

import lxml.html
from email.parser import Parser
import requests
from email.header import decode_header

import sys
from selenium import webdriver
import time
import pymongo
from selenium.common.exceptions import NoSuchElementException, WebDriverException
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.proxy import Proxy, ProxyType
import redis
import requests

from multiprocessing import Pool


def reg_confirm3(username, password):
    try:
        driver = webdriver.Firefox()
        if '163.com' in username:
            driver.get("https://mail.163.com/?msg=authfail#return")
        elif '126.com' in username:
            driver.get("https://mail.126.com/")
        elif 'yeah.net' in username:
            driver.get('https://mail.yeah.net/')
        else:
            return {'code': '17'}
        time.sleep(1)
        driver.switch_to.frame(2)
        time.sleep(1)
        name = driver.find_element_by_xpath('//input[@name="email"]')
        name.clear()
        pw = driver.find_element_by_xpath('//input[@name="password"]')
        pw.clear()
        btn = driver.find_element_by_xpath('//*[@id="dologin"]')
        name.click()
        name.send_keys(username.split("@")[0])
        pw.send_keys(password)
        btn.click()
    # driver.switch_to_default_content()
    except Exception as e:
        print("loging")
        traceback.print_exc()
        # driver.quit()
        input()

    time.sleep(2)
    # driver.save_screenshot('tmp1.png')
    # driver.switch_to_frame(2)
    try:
        tip = driver.find_elements_by_xpath("//*[contains(text(), '帐号或密码错误')]")
        if tip:
            print("%s密码错误" % username)
            driver.quit()
            return {"code": "5"}
        tip = driver.find_elements_by_xpath("//*[contains(text(), '该帐号已被锁定')]")
        if tip:
            print("%s该帐号已被锁定" % username)
            driver.quit()
            return {"code": "6"}
        btn2 = driver.find_element_by_xpath("//*[contains(text(), '继续登录')]")
        btn2.click()
        time.sleep(2)
        driver.switch_to_default_content()
    except WebDriverException:
        driver.switch_to_default_content()
        pass

    except NoSuchElementException:
        # driver.close()
        # driver.quit()
        return {'code': "6"}
    except Exception as e:
        traceback.print_exc()
        print("loging result")
        input()


    while True:
        try:
            # driver.switch_to_default_content()
            driver.switch_to_default_content()
            if "Warn_User_Suspended" in driver.current_url:
                print(driver.current_url)
                return {"code": "6"}
            # is_ok = driver.find_elements_by_xpath("//input[@value='激活我的邮箱']")
            # print(is_ok)
            # if is_ok:
            #     return {"code": "7"}
            mail = driver.find_elements_by_xpath("//*[contains(text(), '收件箱')]")
            if not mail:
                continue
            mail[1].click()
            time.sleep(1)
            reg_mail = driver.find_elements_by_xpath("//*[contains(text(), '中国移动网上商城邮箱验证邮件')]")
            print(reg_mail)
            if reg_mail:
                reg_mail[0].click()
                time.sleep(2)
                iframe = driver.find_elements_by_xpath("//iframe")
                for i in range(len(iframe)):
                    driver.switch_to.frame(i)
                    # print(driver.page_source)
                    link = driver.find_elements_by_xpath('/html/body/div/div[2]/p[4]')
                    reg_link = ""
                    if link:
                        reg_link = link[0].text
                        reg_link = reg_link[:54] + reg_link[-32:]
                        driver.get(reg_link)
                        time.sleep(1)
                        break
                    driver.switch_to_default_content()

                if reg_link:
                    # driver.quit()
                    # s = input()
                    # if s == ' ':
                    #     continue
                    return {"code": '0', 'link': reg_link}
                else:
                    # driver.quit()
                    return {"code": '33', 'link': reg_link}
            else:
                # driver.close()
                # driver.quit()
                print("没收到注册邮件")
                return {"code": '2'}
        finally:
            s = input()
            if s == ' ':
                driver.quit()


if __name__ == '__main__':

    # print(reg_confirm3('wur7910', 'aa7788'))

    #
    username = sys.argv[1]
    rsp = requests.get('http://hh.91link.link:8091/charge/email_get_info.php?username=%s' % username)
    obj = rsp.json()
    print(obj)
    res = reg_confirm3(username, obj['emailpasswd'])
    print(res)
    data = {
        "is_reg": res['code'],
        "username": username
    }
    print(data)
    rsp = requests.post('http://hh.91link.link:8091/charge/email_set_value.php', params=data)
    print(rsp.json())
    print("休息一下")
    time.sleep(1)
